package com.len.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.*;

/**
 * @author songxiangyang
 * @date 2019/3/12
 */
@Component
public class PrestoDataSource {
    private String className;

    @Value("${presto.jdbc.url}")
    private String connUrl;

    @Value("${presto.jdbc.user}")
    private String user;

    @Value("${presto.jdbc.password}")
    private String password;

    public PrestoDataSource() {
        try {
            Class.forName("com.facebook.presto.jdbc.PrestoDriver");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<LinkedHashMap<Object, Object>> getAllData(String sql) {
        List<LinkedHashMap<Object, Object>> data = new ArrayList<>();
        Connection con = null;
        Statement st = null;
        ResultSet re = null;
        try {
            con = DriverManager.getConnection(connUrl, user, password);
            st = con.createStatement();
            re = st.executeQuery(sql);
            ResultSetMetaData md = re.getMetaData();
            while (re.next()) {
                LinkedHashMap<Object, Object> row = new LinkedHashMap<Object, Object>();
                for (int i = 1; i <= md.getColumnCount(); i++) {
                    row.put(md.getColumnName(i), re.getObject(i));
                }
                data.add(row);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (re != null) {
                    re.close();
                }
                if (st != null) {
                    st.close();
                }
                if (con != null) {
                    con.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return data;

    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public String getConnUrl() {
        return connUrl;
    }

    public void setConnUrl(String connUrl) {
        this.connUrl = connUrl;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

